package com.zwz.shiro;

import java.util.Map;
import java.util.Set;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.zwz.bean.ShiroUser;
import com.zwz.bean.SysUsersBean;
import com.zwz.service.baseConfig.SysRoleService;
import com.zwz.service.baseConfig.SysUserService;

/**
 * 自定义realm
 * @author zhangwanzhong
 * 2015年12月27日 下午4:03:49
 */
public class RealmManager extends AuthorizingRealm {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysRoleService sysRoleService; 
	
	/**
	 * 获取身份验证相关信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		SysUsersBean model=new SysUsersBean();
		model.setUser_name(token.getUsername());
		model.setPassword(new String(token.getPassword()));
		Map<String, String> userMap = sysUserService.getUserByAccountPwd(model);
		if(userMap==null){
			throw new UnknownAccountException();// 没找到帐号
		}else if("1".equals(userMap.get("status"))){
			throw new LockedAccountException(); // 帐号锁定
		}else{
			//获得用户角色Id
			Map<String, String> userRoleMap = sysRoleService.getUserRoleIdByUserId(userMap.get("user_id"));
			ShiroUser shiroUser = new ShiroUser(userMap.get("user_id"),
					userMap.get("user_name"), userMap.get("nick_name"),
					userMap.get("status"), userRoleMap.get("role_id"),
					userRoleMap.get("role_name"),userRoleMap.get("role_code"));
		    // 认证缓存信息
			return new SimpleAuthenticationInfo(shiroUser,token.getPassword(),getName());
		}
	}
	/**
	 * 权限认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		if (!SecurityUtils.getSubject().isAuthenticated()) {
			doClearCache(principals);
			SecurityUtils.getSubject().logout();
			return null;
		}
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//加载角色
		Set<String> roles=sysRoleService.getAllRoleCode(shiroUser.getUserId());
		//authorizationInfo.setStringPermissions(per);
		authorizationInfo.setRoles(roles);
		return authorizationInfo;
	}

}
